import { createRouter, createWebHashHistory } from "vue-router";
import Layout from "@/layout/index.vue";

const routes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
    meta: { title: "登录", hideInMenu: true },
  },
  {
    path: "/",
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("@/views/dashboard/index.vue"),
        meta: { title: "首页", icon: "Dashboard" },
      },
    ],
  },
  {
    path: "/user",
    component: Layout,
    children: [
      {
        path: "",
        name: "User",
        component: () => import("@/views/user/index.vue"),
        meta: { title: "用户管理", icon: "User" },
      },
    ],
  },
  {
    path: "/order",
    component: Layout,
    children: [
      {
        path: "",
        name: "Order",
        component: () => import("@/views/order/index.vue"),
        meta: { title: "订单管理", icon: "Tickets" },
      },
    ],
  },
  {
    path: "/court",
    component: Layout,
    children: [
      {
        path: "",
        name: "Court",
        component: () => import("@/views/court/index.vue"),
        meta: { title: "场地管理", icon: "Place" },
      },
    ],
  },
  {
    path: "/bonus",
    component: Layout,
    children: [
      {
        path: "",
        name: "Bonus",
        component: () => import("@/views/coupon/index.vue"),
        meta: { title: "红包管理", icon: "Money" },
      },
    ],
  },
  {
    path: "/image",
    component: Layout,
    children: [
      {
        path: "",
        name: "Image",
        component: () => import("@/views/image/index.vue"),
        meta: { title: "图片管理", icon: "Picture" },
      },
    ],
  },
  {
    path: "/404",
    component: () => import("@/views/error/404.vue"),
    meta: { title: "404", hideInMenu: true },
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("@/views/error/404.vue"),
    meta: { hideInMenu: true },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");

  if (to.path === "/login") {
    if (token) {
      next("/");
    } else {
      next();
    }
  } else {
    if (!token) {
      next("/login");
    } else {
      next();
    }
  }
});

export default router;
